package org.noootsab.gae.games.tzaar.service.impl;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import org.noootsab.gae.games.tzaar.model.Player;
import org.noootsab.gae.games.tzaar.service.GAEUserServiceWrapper;
import org.noootsab.gae.games.tzaar.service.PersistenceManagerFactoryHelper;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.Transactional;
import java.util.logging.*;

/**
 * User: sandy
 * Date: 21-mars-2010
 * Time: 19:35:52
 */
public class GAEUserServiceWrapperImpl implements GAEUserServiceWrapper {
    private static final Logger LOG = Logger.getLogger(GAEUserServiceWrapperImpl.class.getName());

    @Transactional
    public Player getLoggedInUser() {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        if (user == null) {
            return null;
        } else {
            //get persistence manager
            PersistenceManager persistenceManager = PersistenceManagerFactoryHelper.get().getPersistenceManager();
            Player player = null;
            try {
                Query query = persistenceManager.newQuery(Player.class, "userId==\""+user.getUserId()+"\"");
                query.setUnique(true);
                player = (Player) query.execute();
                if (player == null) {
                    player = new Player();
                    player.setUserId(user.getUserId());
                    player.setEmail(new Email(user.getEmail()));
                    //save our entry
                    player = persistenceManager.makePersistent(player);
                    if (player == null) {
                        NullPointerException npe = new NullPointerException("Player is null!");
                        throw npe;
                    } else {
                    }
                }
            } catch (Exception e) {
                LOG.log(Level.SEVERE, "Exception caught when saving player for user id "+user.getUserId()+"!", e);
                e.printStackTrace();
            } finally {
                persistenceManager.close();
            }
            return player;
        }
    }

    public String getLogoutUrl() {
        UserService userService = UserServiceFactory.getUserService();
        return userService.createLogoutURL("/");
    }
}
